import { useEffect, useRef } from 'react';
import { ECharts, EChartsOption, init } from 'echarts';

export default function useECharts(
  elRef: React.MutableRefObject<HTMLDivElement | null>,
  options: EChartsOption,
  isSet = true,
) {
  const chartInstance = useRef<ECharts>();

  useEffect(() => {
    if (!chartInstance.current) {
      chartInstance.current = init(elRef.current!);
    }
    if (!isSet) {
      return;
    }
    chartInstance.current.setOption(options);
  }, [options]);

  const resize = () => {
    chartInstance.current?.resize();
  };

  useEffect(() => {
    window.addEventListener('resize', resize);
    return () => {
      window.removeEventListener('resize', resize);
    };
  }, []);

  return {
    chartInstance,
  };
}
